package cn.edu.scau.cmi.wuyihan.hibernate.dao;

import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.scau.cmi.wuyihan.hibernate.domain.Student;

public class StudentDAO{
	private static final Logger LOGGER = LoggerFactory.getLogger(StudentDAO.class);
	private Session session;
	
	public StudentDAO() {}
	
	public StudentDAO(Session session) {
		this.session = session;
	}
	
	public void save(Student student) {
		LOGGER.debug("saving Student instance");
		try {
			session.save(student);
			LOGGER.debug("save successful");
		}catch (RuntimeException re) {
			LOGGER.error("save failed",re);
			throw re;
		}
	}
	
	public Student findById(Long id) {
		LOGGER.debug("getting Student instance with id: "+id);
		try {
			Student student = (Student) session.get("cn.edu.scau.cmi.wuyihan.hibernate.domain.Student", id);
			return student;
		}catch (RuntimeException re) {
			LOGGER.error("get failed",re);
			throw re;
		}
	}
	
	public void updateName(Student student) {
		LOGGER.debug("updating Student instance");
		try {
			String sql = "update Student s set s.name = ? where s.id=?";
			Query query = session.createQuery(sql);
			query.setParameter(0, student.getName());
			query.setParameter(1, student.getId());
			query.executeUpdate();
			LOGGER.debug("update susscessful");
		}catch (RuntimeException re) {
			LOGGER.error("update failed",re);
			throw re;
		}
	}
	
	public void updateNumber(Student student) {
		LOGGER.debug("updating Student instance");
		try {
			String sql = "update Student s set s.number = ? where s.id =?";
			Query query = session.createQuery(sql);
			query.setParameter(0, student.getNumber());
			query.setParameter(1, student.getId());
			query.executeUpdate();
			LOGGER.debug("update susscessful");
		}catch (RuntimeException re) {
			LOGGER.error("update failed",re);
			throw re;
		}
	}
	
	public void delete(Student student) {
		LOGGER.debug("deleting Student student");
		try {
			Student stu = (Student) session.get(Student.class, student.getId());
			session.delete(stu);
			LOGGER.debug("delete successful");
		}catch (RuntimeException re) {
			LOGGER.error("delete failed");
			throw re;
		}
	}
}
